﻿using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
namespace HurricanePackage
{
    /// <summary>
    /// 对象缓存池
    /// </summary>
    /// <typeparam name="GOAL">缓存的目标对象</typeparam>
    /// <typeparam name="TEMP">构造缓存对象的依赖类</typeparam>
    public abstract class ObjectCache<GOAL, TEMP> 
        where GOAL : ICacheable
    {
        //是否已经初始化
        private bool m_bIsInit;
        //模板对象
        private TEMP m_tTemplateObj;

        //创建的对象缓存池，默认创建最少数量，超出最大数量则删除过多缓存
        private int m_iMinCacheCount = 10;
        private int m_iMaxCacheCount = 50;
        private int m_iAddUnit = 1;
        
        // 警告数量 
        private int m_iIsWarningCount;

        //当前缓存池大小
        private int m_iTotalCreateCount;
        //可使用的数量
        private int m_iEnableCount;
        //还可以使用的缓存对象集合
        [NotNull]
        private List<GOAL> m_lEnableCacheList;

        protected ObjectCache(int _minCount, int _maxCount, int _addUnit = 2)
        {
            m_bIsInit = false;
            m_tTemplateObj = default(TEMP);

            m_iMinCacheCount = _minCount;
            m_iMaxCacheCount = _maxCount;
            m_iIsWarningCount = m_iMaxCacheCount;

            m_iTotalCreateCount = 0;
            m_iEnableCount = 0;
            m_lEnableCacheList = new List<GOAL>();

            m_iAddUnit = _addUnit;
        }
 
        public void Init(TEMP _template)
        {
            lock (this)
            {
                if (m_bIsInit)
                {
#if UNITY_EDITOR
                    //输出错误
                    Debug.LogError("Init Cache Controller multiple times!");
#endif
                    return;
                }
                m_tTemplateObj = _template;
     
                if (m_tTemplateObj != null)
                {
                    //逐个实例化子窗口对象
                    for (int i = 0; i < m_iMaxCacheCount; i++)
                    {
                        GOAL newItem = _CreateItem(m_tTemplateObj);
                        //判断引用
                        if(ReferenceEquals(null,newItem))
                            break;
                        //对缓存对象初始化
                        newItem.Init();
                        //将对象加入可使用的缓存对列
                        m_lEnableCacheList.Add(newItem);
                        m_iTotalCreateCount++;
                        m_iEnableCount++;
                    }
                }
                //初始化标志位
                m_bIsInit = true;
                //调用事件函数
                _OnCacheInit(_template);
            }
        }

        public void Discard()
        {
            //释放所有cache对象
            foreach (var cacheItem in m_lEnableCacheList)
            {
                _DiscardItem(cacheItem);
            }
            //清空引用
            m_lEnableCacheList.Clear();
            m_iEnableCount = 0;
            m_tTemplateObj = default(TEMP);

            _Discard();
        }
        /// <summary>
        /// 取出缓存对象
        /// </summary>
        /// <returns></returns>
        public GOAL PopItem()
        {
            lock (this)
            {
                //没有可用对象时
                if (m_iEnableCount <= 0)
                {
                    //增加缓存对象
                    _AddCache();

                    //缓存数量超标给个警告
                    if (m_iTotalCreateCount > m_iIsWarningCount)
                    {
#if UNITY_EDITOR
                        UnityEngine.Debug.LogError("cache over max num: " + m_iIsWarningCount + "! " + WarningTxt);
#endif
                        m_iIsWarningCount += m_iIsWarningCount / 2;
                        m_iMaxCacheCount = m_iIsWarningCount;
                    }

                }
                else
                {
                    //取出最后一个对象
                    GOAL firstItem = m_lEnableCacheList[m_iEnableCount - 1];
                    m_iEnableCount--;
                    return firstItem;
                }

                return default(GOAL);
            }
        }
        /// <summary>
        /// 放回缓存对象
        /// </summary>
        /// <param name="_item"></param>
        public void PushItem(GOAL _item)
        {
            lock (this)
            {
                if (ReferenceEquals(null, _item))
                    return;

                //设置对象无效
                _ResetItem(_item);
                //放入缓存队列
                if (m_iEnableCount < m_lEnableCacheList.Count)
                    m_lEnableCacheList[m_iEnableCount] = _item;
                else
                    m_lEnableCacheList.Add(_item);
                m_iEnableCount++;
            }
        }

        protected void _AddCache()
        {
            //根据增量创建
            for (int i = 0; i < m_iAddUnit; i++)
            {
                GOAL newItem = _CreateItem(m_tTemplateObj);
                //判断引用
                if (ReferenceEquals(null, newItem))
                    break;
                //对缓存对象初始化
                newItem.Init();
                   // 放入总缓存队列
                m_iTotalCreateCount++;
                //放入缓存队列
                if (m_iEnableCount < m_lEnableCacheList.Count)
                    m_lEnableCacheList[m_iEnableCount] = newItem;
                else
                    m_lEnableCacheList.Add(newItem);
                m_iEnableCount++;
            }
        }

        #region 抽象层
        /// <summary>
        /// 本Cache销毁时触发函数
        /// </summary>
        protected virtual void _Discard()
        {

        }
        /// <summary>
        /// 缓存池超标的警告信息
        /// </summary>
        protected  abstract  string WarningTxt { get; }
        /// <summary>
        /// 初始化回调事件
        /// </summary>
        protected abstract void _OnCacheInit(TEMP _template);
        /// <summary>
        /// 根据模板创建对象
        /// </summary>
        protected abstract GOAL _CreateItem(TEMP _template);
        /// <summary>
        /// 释放对象资源的回调函数
        /// </summary>
        protected abstract void _DiscardItem(GOAL _item);
        /// <summary>
        /// 重置对象资源的回调函数
        /// </summary>
        /// <param name="_item"></param>
        protected abstract void _ResetItem(GOAL _item);

        #endregion

    }
}

